from django.core.management.base import BaseCommand
from django.urls import get_resolver
from django.conf import settings
from accounts.models import Permission


class Command(BaseCommand):
    help = '同步URL路由到权限表，默认同时增删权限'

    def add_arguments(self, parser):
        parser.add_argument(
            '--no-delete',
            action='store_true',
            help='不删除未在URL中定义的权限',
        )

    def handle(self, *args, **options):
        # 获取所有URL名称
        url_names = self.get_all_url_names()
        
        # 过滤掉不需要的权限（如Django admin权限）
        filtered_url_names = [name for name in url_names if not name.startswith('admin:')]
        
        # 创建或更新权限
        created_count = 0
        updated_count = 0
        deleted_count = 0
        
        for url_name in filtered_url_names:
            # 直接使用URL名称作为权限名称
            permission_name = url_name
            print(permission_name)
            
            # 创建或更新权限
            permission, created = Permission.objects.get_or_create(
                url_name=url_name,
                defaults={'name': permission_name}
            )
            
            if created:
                created_count += 1
                self.stdout.write(f'创建权限: {permission_name} ({url_name})')
            else:
                # 更新权限名称（如果需要）
                if permission.name != permission_name:
                    old_name = permission.name
                    permission.name = permission_name
                    permission.save()
                    updated_count += 1
                    self.stdout.write(f'更新权限: {old_name} -> {permission_name} ({url_name})')
        
        # 删除未在URL中定义的权限（除非指定了--no-delete选项）
        if not options['no_delete']:
            existing_permissions = Permission.objects.all()
            for permission in existing_permissions:
                if permission.url_name not in filtered_url_names:
                    permission_name = permission.name
                    url_name = permission.url_name
                    permission.delete()
                    deleted_count += 1
                    self.stdout.write(f'删除权限: {permission_name} ({url_name})')
        
        # 输出统计信息
        self.stdout.write(
            self.style.SUCCESS(
                f'权限同步完成: {created_count}个新权限, {updated_count}个更新权限, {deleted_count}个删除权限'
            )
        )

    def get_all_url_names(self):
        """获取所有URL名称"""
        url_names = []
        self._get_url_names_recursive(get_resolver(), url_names)
        return url_names

    def _get_url_names_recursive(self, resolver, url_names, prefix=''):
        """递归获取URL名称"""
        for pattern in resolver.url_patterns:
            if hasattr(pattern, 'url_patterns'):
                # 这是一个包含子路由的路由
                new_prefix = prefix + (pattern.namespace + ':' if pattern.namespace else '')
                self._get_url_names_recursive(pattern, url_names, new_prefix)
            else:
                # 这是一个具体的URL模式
                if pattern.name:
                    full_name = prefix + pattern.name
                    url_names.append(full_name)

    def generate_permission_name(self, url_name):
        """根据URL名称生成权限名称"""
        # 简单地返回URL名称作为权限名称
        return url_name